<template>
	<view>
		<view class="white">
		</view>
		<view class="wooden-calendar-container">
			<!-- 日历头部 -->
			<view class="calendar-header">
				<button class="nav-btn" @click="prevMonth">◀</button>
				<view class="flex align-center">
					<text class="current-month"
						@click="()=>showCal = !showCal">{{ currentYear }}年{{ currentMonth }}月</text>
					<button class="title-btn" @click="toggle('bottom')">▼</button>
				</view>
				<button class="nav-btn" @click="nextMonth">▶</button>
			</view>
			<view v-show="showCal" class="cal-content">
				<!-- 星期标题 -->
				<view class="week-header">
					<view class="week-day" v-for="day in weekDays" :key="day">{{ day }}</view>
				</view>

				<!-- 日历主体 -->
				<view class="calendar-body">
					<view v-for="(week, weekIndex) in calendarDays" :key="weekIndex" class="calendar-week">
						<view v-for="(day, dayIndex) in week" :key="dayIndex" class="calendar-day" :class="{
				    'current-month': day.isCurrentMonth,
				    'today': day.isToday,
				    'selected': day.dateStr === selectedDate,
				    'has-diary': day.hasDiary
				  }" @click="selectDate(day)">
							<view class="day-content">
								<text class="day-number">{{ day.date }}</text>
								<!-- 当天显示可爱图标 -->
								<view v-if="day.isToday" class="today-icon">🌸</view>
								<!-- 有日记的日期显示小点 -->
								<view v-if="day.hasDiary && !day.isToday" class="today-icon">{{mood[day.allData.mood]}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="aa">
			<view class="diary-preview-list" ref="diaryList">
				<scroll-view v-if="diaryData.length" scroll-y="true" :scroll-with-animation="true"
					:scroll-into-view="scrollIntoView" class="diary-preview-list-view">
					<view v-for="(diary, index) in diaryData" :key="index" class="diary-item" :id="`diary-${diary.id}`">
						<DiaryItemVue :diary="diary"></DiaryItemVue>
					</view>
				</scroll-view>
				<view v-else class="flex just-center" style="margin-top: 200rpx;">
					这个月暂无日记
				</view>
			</view>
		</view>
	</view>
	<Mypopup ref="mypopupRef" type="bottom">
		<uni-popup ref="popupRef" id="popupRefs" type="bottom" background-color="#fff">
			<press-datetime-picker type="year-month" :value="currentDate" :max-date="maxDate" @input="onInput"
				@confirm="confirm" @cancel="cancel" />
		</uni-popup>
	</Mypopup>
	<button type="default" @click="goWrite" class="wb">写日记</button>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch,
		nextTick
	} from 'vue';
	import request from '../../utils/request';
	import {
		useUserStore
	} from '../../store/user';
	import dayjs from 'dayjs';
	import {
		mood
	} from '../../enum';
	import DiaryItemVue from './components/DiaryItem.vue';
	import {
		onPullDownRefresh,
		onReachBottom
	} from '@dcloudio/uni-app'
	import PressDatetimePicker from 'press-ui/press-datetime-picker/press-datetime-picker.vue';
	import {
		getCurrentInstance
	} from 'vue'
	import Mypopup from "./../../components/Mypopup.vue"
	import {
		onShow
	} from '@dcloudio/uni-app'

	const userStore = useUserStore()

	const goWrite = () => {
		uni.navigateTo({
			url: "/pages/write/index"
		})
	}
	const instance = getCurrentInstance()
	const showCal = ref(false)
	const diaryList = ref()
	// 响应式数据
	const currentYear = ref(new Date().getFullYear());
	const currentMonth = ref(new Date().getMonth() + 1);
	const selectedDate = ref('');
	const diaryData = ref([]); // 模拟日记数据

	// 星期标题
	const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

	// 生成日历天数
	const calendarDays = computed(() => {
		const days = [];
		const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
		const lastDay = new Date(currentYear.value, currentMonth.value, 0);
		const prevMonthLastDay = new Date(currentYear.value, currentMonth.value - 1, 0).getDate();

		// 计算月首是星期几
		const firstDayOfWeek = firstDay.getDay();

		// 补充上个月的日期
		for (let i = firstDayOfWeek - 1; i >= 0; i--) {
			const date = prevMonthLastDay - i;
			const month = currentMonth.value === 1 ? 12 : currentMonth.value - 1;
			const year = currentMonth.value === 1 ? currentYear.value - 1 : currentYear.value;
			const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`;

			days.push({
				date,
				month,
				year,
				isCurrentMonth: false,
				isToday: isToday(year, month, date),
				hasDiary: hasDiaryOnDate(dateStr),
				dateStr,
				allData: getData(dateStr)
			});
		}

		// 添加当前月的日期
		for (let i = 1; i <= lastDay.getDate(); i++) {
			const dateStr =
				`${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-${String(i).padStart(2, '0')}`;

			days.push({
				date: i,
				month: currentMonth.value,
				year: currentYear.value,
				isCurrentMonth: true,
				isToday: isToday(currentYear.value, currentMonth.value, i),
				hasDiary: hasDiaryOnDate(dateStr),
				dateStr,
				allData: getData(dateStr)
			});
		}

		// 补充下个月的日期
		const totalDays = days.length;
		const nextMonthDays = 42 - totalDays; // 6行7列
		for (let i = 1; i <= nextMonthDays; i++) {
			const month = currentMonth.value === 12 ? 1 : currentMonth.value + 1;
			const year = currentMonth.value === 12 ? currentYear.value + 1 : currentYear.value;
			const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`;

			days.push({
				date: i,
				month,
				year,
				isCurrentMonth: false,
				isToday: isToday(year, month, i),
				hasDiary: hasDiaryOnDate(dateStr),
				dateStr,
				allData: getData(dateStr)
			});
		}

		// 分割成周
		const weeks = [];
		for (let i = 0; i < 6; i++) {
			weeks.push(days.slice(i * 7, (i + 1) * 7));
		}

		return weeks;
	});

	// 判断是否是今天
	const isToday = (year, month, date) => {
		const today = new Date();
		return (
			today.getFullYear() === year &&
			today.getMonth() + 1 === month &&
			today.getDate() === date
		);
	};

	// 判断某天是否有日记
	const hasDiaryOnDate = (dateStr) => {
		// 模拟数据，实际应从后端获取

		return diaryData.value.some((item) => {
			if (item.recordTime) {
				return item.recordTime.includes(dateStr)
			} else {
				return false
			}

		});
	};

	//获取表情
	const getData = (dateStr) => {
		// 模拟数据，实际应从后端获取
		const item = diaryData.value.filter(item => {
			if (item.recordTime) {
				return item.recordTime.includes(dateStr)
			} else {
				return ''
			}
		})
		if (item.length) {
			return item[0]
		} else {
			return ''
		}
	};

	// 判断选中日期是否有日记
	const hasDiaryOnSelectedDate = computed(() => {
		if (!selectedDate.value) return false;
		return hasDiaryOnDate(selectedDate.value);
	});

	// 上个月
	const prevMonth = () => {
		if (currentMonth.value === 1) {
			currentMonth.value = 12;
			currentYear.value--;
		} else {
			currentMonth.value--;
		}
		getListByMonth(currentYear.value + "-" + currentMonth.value.toString().padStart(2, 0))
	};

	// 下个月
	const nextMonth = () => {
		if (currentMonth.value === 12) {
			currentMonth.value = 1;
			currentYear.value++;
		} else {
			currentMonth.value++;
		}
		getListByMonth(currentYear.value + "-" + currentMonth.value.toString().padStart(2, 0))
	};
	const selectData = ref()
	// 选择日期
	const selectDate = (day) => {
		console.log("day", day);
		selectedDate.value = day.dateStr;
		selectData.value = day.allData
		scrollToItem(day.allData.id)
		showCal.value = !showCal.value
	};

	// 格式化中文日期
	const formatChineseDate = (dateStr) => {
		if (!dateStr) return '';
		const [year, month, day] = dateStr.split('-');
		return `${year}年${parseInt(month)}月${parseInt(day)}日`;
	};

	//获取当月的日历数据
	const getListByMonth = async (month) => {
		const {
			data
		} = await request.post('/diary/byMonth', {
			month: month
		})
		if (data) {
			diaryData.value = data
			if (!selectData.value) {
				selectData.value = getData(dayjs().format("YYYY-MM-DD"))
			}
		}
	}


	const goDetail = (val) => {
		console.log("goDetail++++++++", val);
		uni.navigateTo({
			url: `/pages/index/detail/index?id=${val.id}`,
		})
	}
	watch(() => userStore.token, (val) => {
		if (val) {
			getListByMonth(dayjs().format("YYYY-MM"))
		}
	})

	const scrollIntoView = ref('')

	const scrollToItem = (itemId) => {
		// 设置要滚动到的元素 ID
		scrollIntoView.value = `diary-${itemId}`
	}

	//选择年月相关功能
	const currentDate = ref(new Date().getTime())
	const maxDate = ref(new Date().getTime())

	const onInput = (e) => {

	}
	const confirm = (e) => {
		if (selectedDate.value) {
			const yearMonth = dayjs(e).format("YYYY-MM")
			const yearList = yearMonth.split("-")
			let dateList = selectedDate.value.split("-")
			dateList.splice(0, 2, yearList[0], yearList[1])
			selectedDate.value = dateList.join("-")
			currentMonth.value = Number(dateList[1]);
			currentYear.value = Number(dateList[0]);
			mypopupRef.value.close()
		}
		getListByMonth(currentYear.value + "-" + currentMonth.value.toString().padStart(2, 0))
	}
	const cancel = (e) => {
		mypopupRef.value.close()
	}

	const popupRef = ref()
	const toggle = (val) => {
		mypopupRef.value.open(val);
	}

	const resetPage = () => {
		if (userStore.token) {
			getListByMonth(currentYear.value + "-" + currentMonth.value.toString().padStart(2, 0))
		}
	}

	onShow(() => {
		resetPage()
	})

	// 初始化模拟数据
	onMounted(() => {
		// 模拟一些有日记的日期
		const today = new Date();
		const todayStr =
			`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
		// 默认选中今天
		selectedDate.value = todayStr;
	});

	const mypopupRef = ref()
</script>

<style scoped lang='scss'>
	.wooden-calendar-container {
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx;
		background: rgba(230, 210, 160, 0.6);
		border-radius: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(139, 69, 19, 0.2);
		font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
		position: fixed;
		top: 0;
		z-index: 10;
	}

	.calendar-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx;
	}

	.nav-btn {
		background: #d2b48c;
		color: #8b4513;
		border: none;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 8rpx rgba(139, 69, 19, 0.2);
	}

	.nav-btn:active {
		background: #c19a6b;
		transform: scale(0.95);
	}

	.title-btn {
		/* 		background: #d2b48c; */
		background: transparent;
		color: #8b4513;
		border: none;
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 10rpx;
		/* box-shadow: 0 4rpx 8rpx rgba(139, 69, 19, 0.2); */
	}

	.current-month {
		font-size: 32rpx;
		font-weight: bold;
		color: #8b4513;
	}

	.week-header {
		display: flex;
		background: #d2b48c;
		border-radius: 15rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 8rpx rgba(139, 69, 19, 0.1);
	}

	.week-day {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		color: #8b4513;
		font-weight: bold;
		font-size: 28rpx;
	}

	.calendar-body {
		background-color: rgba(255, 255, 255, 0.7);
		border-radius: 15rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 16rpx rgba(139, 69, 19, 0.1);
	}

	.calendar-week {
		display: flex;
	}

	.calendar-day {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-right: 1rpx solid rgba(210, 180, 140, 0.3);
		border-bottom: 1rpx solid rgba(210, 180, 140, 0.3);
		position: relative;
		transition: all 0.2s ease;
	}

	.calendar-day:last-child {
		border-right: none;
	}

	.calendar-week:last-child .calendar-day {
		border-bottom: none;
	}

	/* 当前月份的日期 */
	.calendar-day.current-month {
		background-color: rgba(255, 255, 255, 0.5);
	}

	/* 非当前月份的日期 */
	.calendar-day:not(.current-month) {
		background-color: rgba(240, 217, 181, 0.3);
		color: #bca68a;
	}

	/* 今天的样式 */
	.calendar-day.today {
		background: linear-gradient(135deg, #fff5e5, #ffe4b6);
		box-shadow: 0 0 20rpx rgba(245, 176, 65, 0.6);
	}

	/* 选中日期的样式 */
	.calendar-day.selected {
		background: linear-gradient(135deg, #d2b48c, #d2b48c);
		box-shadow: 0 0 20rpx rgba(193, 154, 107, 0.6);
		transform: scale(1.05);
		z-index: 1;
	}

	/* 悬停效果 */
	.calendar-day:not(.selected):hover {
		background: rgba(210, 180, 140, 0.4);
		box-shadow: inset 0 0 20rpx rgba(139, 69, 19, 0.2);
	}

	.day-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.day-number {
		font-size: 30rpx;
		margin-bottom: 5rpx;
		color: #8b4513;
		font-weight: 500;
	}

	/* 今天的可爱图标 */
	.today-icon {
		font-size: 24rpx;
		position: absolute;
		top: -28rpx;
		animation: pulse 2s infinite;
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.2);
		}

		100% {
			transform: scale(1);
		}
	}

	/* 有日记的小点 */
	.diary-dot {
		width: 12rpx;
		height: 12rpx;
		background-color: #c19a6b;
		border-radius: 50%;
		position: absolute;
		bottom: 10rpx;
	}

	/* 选中日期信息 */
	.selected-date-info {
		margin-top: 30rpx;
		padding: 20rpx;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 15rpx;
		text-align: center;
		color: #8b4513;
		font-size: 28rpx;
		box-shadow: 0 4rpx 12rpx rgba(139, 69, 19, 0.1);

		&-content {
			display: -webkit-box;
			-webkit-line-clamp: 7;
			/* 显示3行 */
			-webkit-box-orient: vertical;
			overflow: hidden;
			text-overflow: ellipsis;
			font-size: 24rpx;
		}
	}

	.diary-status {
		margin-top: 10rpx;
		font-size: 24rpx;
	}

	.cal-content {
		margin-top: 30rpx;
	}

	.diary-preview-list {
		margin-top: 30rpx;
		/* background: rgba(255, 255, 255, 0.7); */
		border-radius: 15rpx;
		padding: 20rpx;

		&-view {
			/* height: calc(100vh - 120rpx); */
		}
	}

	.diary-date {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.date-number {
		font-size: 48rpx;
		font-weight: bold;
		color: #8b4513;
		margin-right: 10rpx;
	}

	.date-week {
		font-size: 24rpx;
		color: #8b4513;
	}

	.date-status {
		font-size: 20rpx;
		color: #ff6b6b;
		margin-left: 10rpx;
	}

	.diary-content {
		margin-bottom: 15rpx;
	}

	.diary-title {
		font-size: 32rpx;
		color: #8b4513;
		font-weight: 500;
		margin-bottom: 10rpx;
	}

	.diary-text {
		font-size: 28rpx;
		color: #555;
		line-height: 1.5;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
	}

	.diary-images {
		display: flex;
		gap: 10rpx;
		margin-bottom: 15rpx;
		overflow-x: auto;
		white-space: nowrap;
	}

	.diary-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 10rpx;
		object-fit: cover;
	}

	.diary-footer {
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		color: #8b4513;
	}

	.loading-more {
		text-align: center;
		color: #8b4513;
		font-size: 28rpx;
		padding: 20rpx;
	}

	.load-more-btn {
		text-align: center;
		color: #8b4513;
		font-size: 28rpx;
		padding: 20rpx;
		cursor: pointer;
	}

	.load-more-btn:active {
		background: rgba(210, 180, 140, 0.1);
	}

	.no-more-data {
		text-align: center;
		color: #8b4513;
		font-size: 28rpx;
		padding: 20rpx;
	}

	.aa {
		margin-top: 20rpx;
		height: calc(100vh - 100rpx);
		overflow-y: auto;
		background-repeat: no-repeat;
		background-size: cover;
		/* makes the image fill the whole screen */
	}

	.white {
		height: 100rpx;
	}

	.wb {
		width: 120rpx;
		height: 50rpx;
		line-height: 50rpx;
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		font-size: 14px;
		text-align: center;
		background-color: rgba(210, 180, 140, 0.4);
		border-radius: 20rpx;
	}
</style>